
import { Resource, invoke } from '@tauri-apps/api/core';

export type ConnectorDatabaseType = 'sqlite' | 'mysql';
export type ConnectorProtocolType = 'sqlite' | 'mysql' | 'jdbc';

export interface ConnectorDataSource {
    id: number,
    protocol: ConnectorProtocolType,
    url: string,
    database_type: ConnectorDatabaseType,
    username?: string,
    password?: string,
    options?: { [key: string]: string },
}

export const queryForMap = async (dataSource: ConnectorDataSource, sql: string, args: Array<any>, options: any): Promise<Array<{ [key: string]: any }>> => {
    if (!dataSource.protocol) {
        dataSource.protocol = dataSource.database_type;
    }
    let res: Array<any> = await invoke('plugin:mg-connector|query', {
        dataSource: dataSource,
        sql: sql,
        args: args,
        options: options
    });
    console.log(dataSource, res, sql, args);
    let header = res[0];
    let body = res[1];

    return body.map((item: any) => {
        let obj: any = {};
        for (let i = 0; i < header.length; i++) {
            obj[header[i].label] = item[i]
        }
        return obj;
    });
}


export const query = async (dataSource: ConnectorDataSource, sql: string, args: Array<any>, options: any): Promise<{ header: Array<any>, values: Array<Array<any>> }> => {
    if (!dataSource.protocol) {
        dataSource.protocol = dataSource.database_type;
    }
    let res: Array<any> = await invoke('plugin:mg-connector|query', {
        dataSource: dataSource,
        sql: sql,
        args: args,
        options: options
    });
    let header = res[0];
    let body = res[1];
    console.log(body);
    return {
        header: header,
        values: body
    };
}

export const queryOne = async (dataSource: ConnectorDataSource, sql: string, args: Array<any>, options: any): Promise<{ header: Array<any>, value: Array<any> }> => {
    if (!dataSource.protocol) {
        dataSource.protocol = dataSource.database_type;
    }
    let res: Array<any> = await invoke('plugin:mg-connector|query_one', {
        dataSource: dataSource,
        sql: sql,
        args: args,
        options: options
    });
    let header = res[0];
    let body = res[1];
    console.log(body);

    return {
        header: header,
        value: body
    };
}


export const execute = async (dataSource: ConnectorDataSource, sql: string, args: Array<any>, options: { [key: string]: any }): Promise<any> => {
    if (!dataSource.protocol) {
        dataSource.protocol = dataSource.database_type;
    }
    console.log('执行SQL', sql, args);
    let res: Array<any> = await invoke('plugin:mg-connector|execute', {
        dataSource: dataSource,
        sql: sql,
        args: args,
        options: {
            options: options
        }
    });
    console.log(res);
    return res;
}
